package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishDisableFailedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 菜品新增
     * */
    @Override
    @Transactional // 涉及到多张表增删改操作，需要开启事务
    public void addDish(DishDTO dto) {
        // 构建基本信息表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        // 保存信息
        dishMapper.addDish(dish);
        // 构造口味列表
        List<DishFlavor> dishFlavors = dto.getFlavors();
        // 关联菜品id
        if (dishFlavors != null && !dishFlavors.isEmpty()) {
            dishFlavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            // 批量插入
            dishFlavorMapper.insertBatch(dishFlavors);
        }
    }
    /**
     * 菜品分页查询
     * */
    @Override
    public PageResult getDishPage(DishPageQueryDTO dto) {
        // 设置分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> page = dishMapper.list(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }
    /**
    * 删除菜品
    * */
    @Transactional
    @Override
    public void delete(List<Long> ids) {
        // 判断菜品是否起售
        ids.forEach(id -> {
            Dish dis = dishMapper.getById(id);
            if (dis.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        // 判断菜品是否被套餐关联
        Integer count = setmealDishMapper.countByDishId(ids);
        if (count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 删除菜品基本信息表
        dishMapper.deleteBatch(ids);

        // 删除口味基本信息表
        dishFlavorMapper.deleteBatch(ids);
    }
    /**
     * 根据id查询菜品
     * */
    @Override
    public DishVO getDishById(Long id) {
        DishVO dishVO = new DishVO();
        // 查询基本信息
        Dish dish = dishMapper.getById(id);
        // 复制dish信息到vo
        BeanUtils.copyProperties(dish,dishVO);
        // 查询口味信息
        List<DishFlavor> list = dishFlavorMapper.getByDishId(id);
        // 补充口味信息
        dishVO.setFlavors(list);
        return dishVO;
    }
    /**
     * 修改菜品
     * */
    @Override
    @Transactional
    public void updateDish(DishDTO dto) {
        Dish dish = new Dish();
        // 构建表对应的实体对象
        BeanUtils.copyProperties(dto, dish);
        // 修改菜品基本信息
        dishMapper.updateDish(dish);
        // 修改口味列表信息
        List<DishFlavor> dishFlavors = dto.getFlavors();
        // 先删除所有口味信息，再重写添加
        List<Long> dishIds = new ArrayList<>();
        dishIds.add(dto.getId());
        dishFlavorMapper.deleteBatch(dishIds);
        // 如果有新信息，需要关联菜品id
        if (dishFlavors!=null && !dishFlavors.isEmpty()){
            dishFlavors.forEach((dishFlavor) -> {
                dishFlavor.setDishId(dish.getId());
            });
            // 添加新的
            dishFlavorMapper.insertBatch(dishFlavors);
        }
    }
    /**
     * 修改商品状态
     * */
    @Override
    public void updateDishStatus(Long id, Integer status) {
        // 如果停售时，需要判断当前菜品关联套餐是否停售
        if(status == StatusConstant.DISABLE){
            List<Integer> statusList = setmealDishMapper.getSetmealStatus(id);
            statusList.forEach((setmealStatus) -> {
                if(setmealStatus == StatusConstant.ENABLE){
                    throw new DishDisableFailedException(MessageConstant.DISH_DISABLED_FAILED);
                }
            });
        }
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.updateDish(dish);
    }
    /**
     * 根据分类id查询菜品
     * */
    @Override
    public List<Dish> getList(Long id) {
        List<Dish> dishes = dishMapper.getListByCategoryId(id);
        return dishes;
    }
    /**
     * 根据类别id条件查询启售中的菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listBy(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
